﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    private static object lock_ = new object();

    public static T Instance { 
        get 
        {
            lock (lock_)
            {
                if (instance == null)
                {
                    instance = (T)FindObjectOfType(typeof(T));
                    if (FindObjectsOfType(typeof(T)).Length > 1)
                    {
                        Debug.LogError("场景中不止有一个该对象：" + instance.name);
                    }
                    if (instance == null)
                    {
                        GameObject go = new GameObject();
                        instance = go.AddComponent<T>();
                        go.name = typeof(T).Name;
                        //DontDestroyOnLoad(go);如果有需求
                    }
                }return instance;
            }

            //Object[] objs = Object.FindObjectsOfType(typeof(T));
            //if (objs.Length == 1)
            //{
            //    instance =(T) objs[0];
            //}
            //else if (objs.Length > 1)
            //{
            //    Debug.LogError("不为单例");
            //}
            //else
            //{
            //    GameObject go = new GameObject();
            //    instance = go.AddComponent<T>();
            //    go.name = instance.name;
            //}
            
            //先从场景里面找T
            //有T就直接返回T = instan
            //场景里面找到多于1个T，直接报错
            //场景里面没有T
            //创建一个空物体，T挂载到空物体上 此时t = instance
            
        }
    }
}
